package org.misty.redis.util;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;

/**
 * @author Misty on 2020-06-01
 */
public class Util {
    private Util() {
    }

    public static void checkArgument(boolean b, String errorMessageTemplate, Object p1) {
        if (!b) {
            throw new IllegalArgumentException(String.format(errorMessageTemplate != null ? errorMessageTemplate : "%s", p1));
        }
    }

    @Deprecated
    public static String copyToString(URL url) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(url.toURI()));
            return new String(bytes, StandardCharsets.UTF_8);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static String copyToString(InputStream in) {
        byte[] buf = new byte[1024];
        int len;
        try (ByteArrayOutputStream os = new ByteArrayOutputStream();
             InputStream is = in) {
            while ((len = is.read(buf)) != -1) {
                os.write(buf, 0, len);
            }
            return os.toString(StandardCharsets.UTF_8.name());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
